package com.xm.xmapp.customview;

import android.content.Context;
import android.os.Handler;
import android.util.AttributeSet;
import android.widget.TextView;

public class TimerTaskTextView extends TextView {

	public interface StopTimerTask {
		void startTimer();
		void stopTimer();
	}
	int time;
	StopTimerTask stopTimerTask;
	public TimerTaskTextView(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		
	}
	public TimerTaskTextView(Context context) {
		super(context);
	}

	public TimerTaskTextView(Context context, AttributeSet attrs) {
		super(context, attrs);
	}

	public StopTimerTask getStopTimerTask() {
		return stopTimerTask;
	}
	public void setStopTimerTask(StopTimerTask stopTimerTask) {
		this.stopTimerTask = stopTimerTask;
	}
	public int getTime() {
		return time;
	}
	public void setTime(int time) {
		this.time = time;
	}
	final Handler handler = new Handler();
	public void startTimerTask(int times) {
		handler.removeCallbacksAndMessages(null);
		time = times;
		String str = ((time / 60) > 9 ? (time / 60)
				: ("0" + (time / 60)))
				+ ":"
				+ ((time % 60) > 9 ? (time % 60)
						: ("0" + (time % 60)));
		setText(str);
		Runnable runnable = new Runnable() {
			@Override
			public void run() {
				time--;
				if (time > 0) {
					String str = ((time / 60) > 9 ? (time / 60)
							: ("0" + (time / 60)))
							+ ":"
							+ ((time % 60) > 9 ? (time % 60)
									: ("0" + (time % 60)));
					setText(str);
					handler.postDelayed(this, 1000);
				} else {
					stopTimerTask();
					setText("00:00");
				}

			}
		};
		handler.postDelayed(runnable, 1000); 
	}

	public void stopTimerTask() {
		time = 0;
		handler.removeCallbacksAndMessages(null);
		if(stopTimerTask!=null)
			stopTimerTask.stopTimer();
		stopTimerTask = null;
		
	}

}
